﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Text;
using System.Web;
 using System.Text.RegularExpressions;
using System.Diagnostics;

namespace Ajax.Common
{
    /// <summary>
    /// 取得Http客户端信息
    /// </summary>
    public class HttpClient
    {

        #region 穿过代理服务器取远程用户真实IP地址
        /// <summary>
        /// 穿过代理服务器取远程用户真实IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetIP()
        {
            return GetIP(HttpContext.Current);
        }

        public static string GetIP(HttpContext current)
        {
            try
            {
                string IP;
                if (current.Request.ServerVariables["HTTP_VIA"] != null)
                {
                    IP = current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
                }
                else
                {
                    IP = current.Request.ServerVariables["REMOTE_ADDR"].ToString();
                }
                IP = IP.Replace("::1", "127.0.0.1");

                return IP;
            }
            catch
            {
                return "0.0.0.0";
            }
        }
        #endregion

        #region 通过一个URL到文件名
        /// <summary>
        /// 通过一个URL到文件名
        /// </summary>
        /// <param name="URL"></param>
        /// <returns></returns>
        public static string URLFileName(string URL)
        {
            try
            {
                int Index = URL.LastIndexOf('/') + 1;//移除前没有用的字符，只保留文件名和后缀
                return URL.Remove(0, Index);
            }
            catch
            {
                return URL;
            }
        }
        #endregion


        #region 获取客户端MAC地址
        //这里是关键函数了
        public string GetCustomerMac(string IP)
        {
            string dirResults = "";
            ProcessStartInfo psi = new ProcessStartInfo();
            Process proc = new Process();
            psi.FileName = "nbtstat";
            psi.RedirectStandardInput = false;
            psi.RedirectStandardOutput = true;
            psi.Arguments = "-a " + IP;
            psi.UseShellExecute = false;
            proc = Process.Start(psi);
            dirResults = proc.StandardOutput.ReadToEnd();
            proc.WaitForExit();

            //匹配mac地址
            Match m = Regex.Match(dirResults, "\\w+\\-\\w+\\-\\w+\\-\\w+\\-\\w+\\-\\w\\w");

            //若匹配成功则返回mac，否则返回找不到主机信息
            if (m.Success == true)
            {
                return m.ToString();
            }
            else
            {
                return null;
            }
        }
        #endregion
    }
}